//
//  ZYCAttendanceSummaryViewController.m
//  ZDSC
//
//  Created by 张威 on 2021/10/19.
//

#import "ZYCAttendanceSummaryViewController.h"
#import "BTImageTitleButton.h"
#import <xlsxwriter/xlsxwriter.h>
#import "ZYCTourRecordMenuView.h"
#import "ZYCAttendanceSummaryCell.h"
#import "ZYCAttendanceSummaryBottomView.h"
#import "ZYCAttendanceExportRecordsViewController.h"
#import "ZYCAttendanceSummaryDetailViewController.h"
#import "ZYCSchoolAttendanceStatisticsModel.h"
#import "ZYCSelectPastYearMonthView.h"
#import "ZYCCommonSelectObjectPickerView.h"
#import "ZYCCommonBaseModel.h"
#import "SESSFileLookController.h"
#import "NSDateExtra.h"
#import "ZYCUserLoginModel.h"




@interface ZYCAttendanceSummaryViewController ()<UITableViewDataSource,UITableViewDelegate,ZYCTourRecordMenuViewDelegate,ZYCCommonSelectObjectPickerViewDelegate,ZYCAttendanceSummaryBottomViewDelegate>
@property (nonatomic, strong) BTImageTitleButton *rightButton;
@property (nonatomic, strong) ZYCTourRecordMenuView *menuView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray *dataSource;
@property (nonatomic, strong) ZYCAttendanceSummaryBottomView *footerView;
@property (nonatomic, strong) ZYCSchoolAttendanceStatisticsModel *model;
@property (nonatomic, strong) ZYCSelectPastYearMonthView *dateSelectView;
@property (nonatomic, strong) ZYCCommonSelectObjectPickerView *postPickerView;


@property (nonatomic, assign) int rowNum; // 已加载到的行数

@property (nonatomic, strong) NSArray *listExportColumn;
@property (nonatomic, strong) NSArray <NSDictionary *>*listExportData;

@property (nonatomic, strong) NSDateFormatter *dateFormatter;
@property (nonatomic, copy) NSString *teacherId;

@end

@implementation ZYCAttendanceSummaryViewController

#pragma mark - 生命周期函数
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"考勤汇总";
   NSString *leftStr = [NSString stringWithFormat:@"%@", [NSDateExtra getDateStringWithDateString:self.attendanceDate currenDateFormat:@"yyyy-MM-dd" dateFormat:@"yyyy年MM月"]];
    self.menuView.leftStr = leftStr;
    self.menuView.rightStr = self.postName;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.rightButton];
    [self.view addSubview:self.menuView];
    [self.view addSubview:self.tableView];
    self.tableView.tableFooterView = self.footerView;
    
    
    ZYCUserLoginModel *userLogin = [ZYCUserLoginModel userLogin];
    self.teacherId = userLogin.userId;
    [self loadTeacherMonthCensus];
}




#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataSource.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ZYCAttendanceSummaryCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ZYCAttendanceSummaryCell class]) forIndexPath:indexPath];
    NSDictionary *dict = self.dataSource[indexPath.section];
    cell.titleString = dict[@"title"];
    switch (indexPath.section) {
        case 0:{
            cell.contentString = [NSString stringWithFormat:@"%@人",self.model.countZC];
            break;
        }
        case 1:{
            cell.contentString =  [NSString stringWithFormat:@"%@人",self.model.countCD];
            break;
        }
        case 2:{
            cell.contentString = [NSString stringWithFormat:@"%@人",self.model.countZT];
            break;
        }
        case 3:{
            cell.contentString = [NSString stringWithFormat:@"%@人",self.model.countQK];
            break;
        }
        case 4:{
            cell.contentString = [NSString stringWithFormat:@"%@人",self.model.countQJ];
            break;
        }
        case 5:{
            cell.contentString = [NSString stringWithFormat:@"%@人",self.model.countJB];
            break;
        }
        default:
            break;
    }
    return cell;
}

-(CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 5.0f;
    }
    return 1.5f;
}

-(CGFloat) tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01f;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    ZYCAttendanceSummaryDetailViewController *vc = [ZYCAttendanceSummaryDetailViewController new];
    NSDictionary *dict = self.dataSource[indexPath.section];
    vc.titleString = dict[@"title"];
    vc.status = dict[@"status"];
    vc.attendanceDate = self.attendanceDate;
    vc.postId = self.postId;
    vc.postName = self.postName;
    vc.postArr = self.postArr;
    [self.navigationController pushViewController:vc animated:YES];
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [UIView new];
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [UIView new];
}


#pragma mark - ZYCAttendanceSummaryBottomViewDelegate
- (void)attendanceSummaryBottomViewDidExportExcel{
    [self exportExcelRecords];
//    [self testExport];
}
#pragma mark - ZYCTourRecordMenuViewDelegate
- (void)tourRecordMenuViewClickLeft{
    [self.dateSelectView show];
}
- (void)tourRecordMenuViewClickRight{
    [self.postPickerView show];
}


#pragma mark - ZYCCommonSelectObjectPickerViewDelegate
- (void)selectObjectPickerView:(ZYCCommonSelectObjectPickerView *)pickerView DidClickModel:(ZYCCommonBaseModel *)model{
    if (pickerView == self.postPickerView) {
        self.postId = model.nameId;
        self.postName = model.name;
        self.menuView.rightStr = model.name;
        [self loadTeacherMonthCensus];
    }
}
#pragma mark - action
- (void)clickRightItem:(UIButton *)sender{
    ZYCAttendanceExportRecordsViewController *vc = [[ZYCAttendanceExportRecordsViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark - getters


- (NSDateFormatter *)dateFormatter {
    if (!_dateFormatter) {
        _dateFormatter = [[NSDateFormatter alloc] init];
        [_dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    }
    return _dateFormatter;
}
- (NSArray *)listExportColumn {
    if (!_listExportColumn) {
        _listExportColumn = [[NSArray alloc] init];
    }
    return _listExportColumn;
}

- (NSArray *)listExportData {
    if (!_listExportData) {
        _listExportData = [[NSArray alloc] init];
    }
    return _listExportData;
}

- (ZYCCommonSelectObjectPickerView *)postPickerView {
    if (!_postPickerView) {
        _postPickerView = [[ZYCCommonSelectObjectPickerView alloc] init];
        _postPickerView.tipString = @"请选择岗位";
        _postPickerView.dataSource = self.postArr;
        _postPickerView.delegate = self;
        [self.navigationController.view addSubview:_postPickerView];
    }
    return _postPickerView;
}

- (ZYCSelectPastYearMonthView *)dateSelectView {
    ZYCWeakSelf
    if (!_dateSelectView) {
        _dateSelectView = [[ZYCSelectPastYearMonthView alloc] init];
        _dateSelectView.tipString = @"请选择时间";
        _dateSelectView.currentDate = [NSDate date];
        _dateSelectView.confirmAction = ^(NSString * _Nonnull dateStr) {
            weakSelf.attendanceDate = [NSString stringWithFormat:@"%@-01",dateStr];
            weakSelf.menuView.leftStr = [NSString stringWithFormat:@"%@", [NSDateExtra getDateStringWithDateString:dateStr currenDateFormat:@"yyyy-MM" dateFormat:@"yyyy年MM月"]];
            [weakSelf loadTeacherMonthCensus];
        };
        [self.navigationController.view addSubview:_dateSelectView];
    }
    return _dateSelectView;
}

- (ZYCAttendanceSummaryBottomView *)footerView {
    if (!_footerView) {
        _footerView = [[ZYCAttendanceSummaryBottomView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 215.f)];
        _footerView.delegate = self;
    }
    return _footerView;
}
- (NSArray *)dataSource {
    if (!_dataSource) {
        _dataSource = @[@{@"title":@"正常",@"status":@"1"},
                        @{@"title":@"迟到",@"status":@"2"},
                        @{@"title":@"早退",@"status":@"3"},
                        @{@"title":@"缺卡",@"status":@"4"},
                        @{@"title":@"请假",@"status":@"5"},
                        @{@"title":@"加班",@"status":@"6"},
        ];
    }
    return _dataSource;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.menuView.frame), kScreenWidth, kScreenHeight - CGRectGetMaxY(self.menuView.frame)-safeAreaBottomHeight) style:UITableViewStyleGrouped];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerClass:[ZYCAttendanceSummaryCell class] forCellReuseIdentifier:NSStringFromClass([ZYCAttendanceSummaryCell class])];
    }
    return _tableView;
}


- (ZYCTourRecordMenuView *)menuView {
    if (!_menuView) {
        _menuView = [[ZYCTourRecordMenuView alloc] initWithFrame:CGRectMake(0, kNavBarAndStatusBarHeight, kScreenWidth, 46.0f)];
        _menuView.leftStr = @"日期";
        _menuView.rightStr = @"全部岗位";
        _menuView.delegate = self;
    }
    return _menuView;
}
- (BTImageTitleButton *)rightButton {
    if (!_rightButton) {
        _rightButton = [[BTImageTitleButton alloc] init];
        [_rightButton setImage:[UIImage imageNamed:@"dcjl"] forState:UIControlStateNormal];
        [_rightButton setTitle:@"导出记录" forState:UIControlStateNormal];
        [_rightButton setTitleColor:HEX_RGB(kTitleWhiteColor) forState:UIControlStateNormal];
        _rightButton.titleLabel.font = kCustomFont(@"PingFangSC-Regular", 15.0f);
        [_rightButton addTarget:self action:@selector(clickRightItem:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _rightButton;
}

#pragma mark - 网络请求
- (void)loadTeacherMonthCensus{
    NSDictionary *params = @{
        @"attendanceDate":self.attendanceDate,
        @"postId":self.postId
    };
    [MrjSVProgressHUD showWithStatus:@"加载中..."];
    [[URLManager sharedURLManager] postUrlString:Appliance_Post_TeacherMonthCensus requestService:RequestServiceWorkBench parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
        } success:^(id  _Nullable responseObject) {
            [MrjSVProgressHUD dismiss];
            if (SUCCESS(responseObject[@"code"])) {
                ZYCSchoolAttendanceStatisticsModel *model = [ZYCSchoolAttendanceStatisticsModel yy_modelWithDictionary:responseObject[@"body"]];
                self.model = model;
                [self.tableView reloadData];
            }else{
                [MrjToast makeToast:responseObject[@"message"] makeView:self.view];
            }
        } failure:^(NSError * _Nonnull error) {
            
        }];
}

- (void)exportExcelRecords{
    NSDictionary *params = @{
        @"attendanceDate":self.attendanceDate,
        @"postId":self.postId,
        @"teacherId":self.teacherId
    };
    [MrjSVProgressHUD showWithStatus:@"导出中..."];
    [[URLManager sharedURLManager] postUrlString:Appliance_Post_AppAttendanceExport requestService:RequestServiceWorkBench parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(id  _Nullable responseObject) {
            [MrjSVProgressHUD dismiss];
            if (SUCCESS(responseObject[@"code"])) {
                NSArray *listExportColumn = responseObject[@"body"][@"listExportColumn"];//柱子
                self.listExportColumn = listExportColumn;
                NSArray <NSDictionary *>*listExportData = responseObject[@"body"][@"listExportData"];
                self.listExportData = listExportData;
                
                [self exportExcelTypeXlsx];
            }else{
                [MrjToast makeToast:responseObject[@"message"] makeView:self.view];
            }
        } failure:^(NSError * _Nonnull error) {
            
        }];
}

- (NSString *)createAttendanceSummaryPathFilePath{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;
    NSString *attendanceSummaryPath = [cachePath stringByAppendingPathComponent:@"attendanceSummary"];
    // 创建文件夹(考勤汇总)
    [fileManager createDirectoryAtPath:attendanceSummaryPath withIntermediateDirectories:YES attributes:nil error:nil];
    return attendanceSummaryPath;
}

- (void)exportExcelTypeXlsx{
    self.rowNum = 0;

    NSString *filePath = [[self createAttendanceSummaryPathFilePath] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@%@.xlsx",[self.dateFormatter stringFromDate:[NSDate date]],self.postName]];
    NSURL *url = [NSURL fileURLWithPath:filePath];
    
    lxw_workbook  *workbook  = workbook_new([filePath UTF8String]);// 创建新xlsx文件，路径需要转成c字符串
    lxw_worksheet *worksheet = workbook_add_worksheet(workbook, NULL);// 创建sheet
    
    worksheet_set_column(worksheet, 1, 2, 30, NULL); // B、C两列宽度（1:起始列 2:终始列 30:列宽）
    
    
    lxw_format *format = workbook_add_format(workbook);
    format_set_bold(format);
    format_set_font_color(format, LXW_COLOR_RED);
     
//    // Use the format to change the text format in a cell.
//    worksheet_write_string(worksheet, 0, 0, "Hello", format);
    
    [self.listExportColumn enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        uint32_t lxw_row_t = (uint32_t)idx;
        worksheet_write_string(worksheet, self.rowNum, lxw_row_t , [obj UTF8String], NULL);
    }];
    
    
    [self.listExportData enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSDictionary *dict = obj;
        NSString *teacherName = dict[@"teacherName"];
        NSString *deptName = dict[@"deptName"];
        NSString *postName = dict[@"postName"];
        NSString *countCQ = dict[@"countCQ"];
        NSString *countXX = dict[@"countXX"];

        NSString *lateCount = dict[@"lateCount"];
        NSString *earlyCount = dict[@"earlyCount"];
        NSString *missingCardCount = dict[@"missingCardCount"];
        NSString *daySHJ = dict[@"daySHJ"];
        NSString *dayBJ = dict[@"dayBJ"];

        NSString *dayYGJ = dict[@"dayYGJ"];
        NSString *dayNJ = dict[@"dayNJ"];
        NSString *dayHJ = dict[@"dayHJ"];
        NSString *dayCJ = dict[@"dayCJ"];
        NSString *daySJ = dict[@"daySJ"];

        NSString *dayGSJ = dict[@"dayGSJ"];
        NSString *workOvertimeLeave = dict[@"workOvertimeLeave"];

        uint32_t lxw_row_t = (uint32_t)idx;

        worksheet_write_string(worksheet, lxw_row_t + 1, 0, [teacherName UTF8String], NULL);
        worksheet_write_string(worksheet, lxw_row_t + 1, 1, [deptName UTF8String], NULL);
        worksheet_write_string(worksheet, lxw_row_t + 1, 2, [postName UTF8String], NULL);
        worksheet_write_number(worksheet, lxw_row_t + 1, 3, [countCQ doubleValue], NULL);
        worksheet_write_number(worksheet, lxw_row_t + 1, 4, [countXX doubleValue], NULL);

        worksheet_write_number(worksheet, lxw_row_t + 1, 5, [lateCount doubleValue], NULL);
        worksheet_write_number(worksheet, lxw_row_t + 1, 6, [earlyCount doubleValue], NULL);
        worksheet_write_number(worksheet, lxw_row_t + 1, 7, [missingCardCount doubleValue], NULL);
        worksheet_write_number(worksheet, lxw_row_t + 1, 8, [daySHJ doubleValue], NULL);
        worksheet_write_number(worksheet, lxw_row_t + 1, 9, [dayBJ doubleValue], NULL);

        worksheet_write_number(worksheet, lxw_row_t + 1, 10, [dayYGJ doubleValue], NULL);
        worksheet_write_number(worksheet, lxw_row_t + 1, 11, [dayNJ doubleValue], NULL);
        worksheet_write_number(worksheet, lxw_row_t + 1, 12, [dayHJ doubleValue], NULL);
        worksheet_write_number(worksheet, lxw_row_t + 1, 13, [dayCJ doubleValue], NULL);
        worksheet_write_number(worksheet, lxw_row_t + 1, 14, [daySJ doubleValue], NULL);

        worksheet_write_number(worksheet, lxw_row_t + 1, 15, [dayGSJ doubleValue], NULL);
        worksheet_write_number(worksheet, lxw_row_t + 1, 16, [workOvertimeLeave doubleValue], NULL);


    }];
    
    //关闭，保存文件
    workbook_close(workbook);
    
    
    SESSFileLookController *vc = [[SESSFileLookController alloc] initWithFilePath:url];
    vc.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:vc animated:YES completion:nil];

}





/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
